<template>
  <!--  监控抓拍-->
  <div>
    <el-row :gutter="15">
      <el-col :span="4">
        <div style="height: 50vh;">
          <organization-tree v-model="deptTree" ref="deptTree" :changeOnSelect='true' placeholder="选择管养单位"
                             @change="selectOrgHandel">
          </organization-tree>
        </div>
        <div style="height: 50vh;">
          <road-tree v-model="roadTree" ref="roadTree" :changeOnSelect='true' placeholder="选择管养单位"
                     @change="selectOrgHandel1">
          </road-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <!--        时间筛查-->
        <div style="margin-left: 20px;width: 500px;display: inline-block">
          <el-date-picker
            :clearable="false"
            style="width:100%;min-width:240px;height: 40px"
            size="small"
            value-format="timestamp"
            v-model="timerArray"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="预警开始日期"
            end-placeholder="预警结束日期">
          </el-date-picker>
        </div>
        <el-button style="margin-left: 20px;margin-top: 10px" class="common_btn-defalut" icon="el-icon-search"
                   @click="search">搜索
        </el-button>
        <el-container class="content">
          <el-header class="heads">
            <div class="toolbars" style="padding-left: 20px;margin-top:10px;display: flex">
              <el-button class="common_btn-small" plain size="small" icon="el-icon-plus" @click="downloadImage"
                         style="margin-right: 30px">下载照片
              </el-button>
              <el-tooltip class="item" effect="dark" content="请选择至布控点，方可点击按钮" placement="top-start"
                          :disabled="isTooltip">
                <div style="width: 100px;margin-right: 30px">
                  <el-button style="margin-right: 30px" class="common_btn-small" plain size="small" icon="el-icon-bell"
                             @click="action(0)" :disabled="isDisabled" :class="isDisabled==true?'btnNo':''">
                    立即拍照
                  </el-button>
                </div>

              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="请选择至布控点，方可点击按钮" placement="top-start"
                          :disabled="isTooltip">
                <div style="width: 100px;margin-right: 30px">
                  <el-button style="margin-right: 30px" class="common_btn-small" plain size="small" icon="el-icon-bell"
                             @click="action(1)" :disabled="isDisabled " :class="isDisabled==true?'btnNo':''">
                    立即录像
                  </el-button>
                </div>

              </el-tooltip>
              <el-button style="margin-right: 30px" class="common_btn-small" plain size="small" icon="el-icon-bell"
                         @click="pushAlert">
                推送报警信息
              </el-button>
            </div>
          </el-header>
          <div class="middle">
            <el-checkbox-group v-model="card.checkedCard" style="width: 100%">
              <el-card
                shadow="always"
                class="base_img"
                :body-style="{ padding: '0px' }"
                v-for="(item, index) in imgList"
                style="width: 19%;text-align: center;margin: 0 0.5%;margin-bottom: 50px;"
                :key="item.photoUrl">

                <el-image v-if="item.photoUrl.indexOf('.mp4') > -1" class="base_img-item" @click="play(item.photoUrl)"
                          :src="require('./playMp4.png')"></el-image>
                <el-image v-else class="base_img-item" @click="previewImg(index)"
                          :src="constUrl+item.photoUrl"></el-image>
                <div class="base_img-time flex-between">
                  <el-checkbox class="big-checkbox hide-checkbox-text" :label="item"
                               :key="item.id" style="display: block;margin-left: 30px;margin-right:20px"><br/>
                  </el-checkbox>
                  <em style="display: inline-block;width: 210px;text-align: left">
                    <p style="margin-top: 10px"><em style="color: #1990FE;font-weight: 600">拍摄时间：</em>{{item.bizTime |
                      formatTimer}}</p>
                    <p><em style="color: #1990FE;font-weight: 600">路线：</em>{{item.roadName}}</p>
                    <p><em style="color: #1990FE;font-weight: 600">区间：</em>{{item.roadSectionName}}</p>
                    <p><em style="color: #1990FE;font-weight: 600">布控点：</em> {{item.arrangementName}}</p>
                  </em>
                </div>
              </el-card>
            </el-checkbox-group>
          </div>
          <!--分页器-->
          <el-pagination style="margin-right: 50px"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="form1.page"
                         :page-size="form1.pageSize"
                         :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                         layout="sizes, prev, pager, next"
                         :total="form1.total">
          </el-pagination>


        </el-container>
      </el-col>
    </el-row>
    <!--  报警信息弹窗-->
    <el-dialog
      title="推送报警信息"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="400px">
      <el-card shadow="hover">
        <el-row>
          <el-col :span="24">
            <div class="row-detail">
              <div class="row-detail-item">
                <label class="info-label">报警时间:</label>
                <div class="info-content">{{pushAlertInfo.alertTime | formatTimer}}</div>
              </div>
              <div class="row-detail-item">
                <label class="info-label">报警位置信息:</label>
                <div class="info-content"> {{pushAlertInfo.locationInfo}}
                </div>
              </div>
            </div>
            <el-row>
              <el-col>
                <p><label class="info-label">报警图片:</label></p>
                <hr/>
              </el-col>
              <el-col>
                <el-carousel height="200px" arrow="always" :autoplay="false">
                  <el-carousel-item v-for="url in  pushAlertInfo.photoUrlList" :key="url">
                    <img style="width: 500px;height:300px" :src="constUrl+url"/>
                  </el-carousel-item>
                </el-carousel>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
      <el-row>
        <el-form :model="pushAlertInfo" :rules="rules" ref="record">
          <el-form-item prop="pushNumber" label="手机号码:">
            <el-input placeholder="请输入接收人手机号" style="width: 240px;" v-model="pushAlertInfo.pushNumber"
                      clearable validate-event></el-input>
          </el-form-item>
        </el-form>
      </el-row>

      <p style="text-align: center;font-size: 10px;color: dodgerblue">接收者会收到短信通知，可在'报警推送记录'菜单中查询历史</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateForm" style="background: #1990FE">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="视频播放"
      v-if="playMp4"
      :visible.sync="playMp4"
      :close-on-click-modal="false"
      width="1080px">
      <video  id="singleVideo" controls autoplay preload="none" class="video-js vjs-default-skin" ></video>
    </el-dialog>
    <picture-viewer ref="imageViewer"></picture-viewer>
  </div>
</template>
<script>
import roadTree from '@/components/road-tree/all1'
import {
  getArrangementList, downloadPhotos, actionNow
} from '@/services/model/road-control'
import OrganizationTree from '@/components/organization-tree/all1'
import PictureViewer from '@/components/picture-viewer'
import {
  getAllPhoto
} from '@/services/model/camera'
import Enums from '@/utils/enums'
import constUrl from '@/services/env'
import 'video.js/dist/video-js.css'
import videojs from 'video.js';
import 'videojs-contrib-hls'
import Format from '@/utils/format'
import {addPushRecord} from '@/services/model/early-warning'
const RULES = {
  pushNumber: {required: true, validator: CHECK_PHONE},
}
import {CHECK_PHONE} from "./validator";
const timer = 30 * 24 * 3600 * 1000
export default {
  mixins:[Enums],
  components: {PictureViewer, OrganizationTree, roadTree},
  data() {
    return {
      //存放时间
      form2: {
        startCreateTime: Date.parse(new Date()) - timer,
        endCreateTime: Date.parse(new Date()),
      },
      // 时间选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }],
        onPick: obj => {
          this.picerMinDate = new Date(obj.minDate).getTime()
        },
        disabledDate: time => {
          if (this.picerMinDate) {
            // 最多可选3个月
            const LIMIT = 90 * 24 * 60 * 60 * 1000
            const maxTime = this.picerMinDate + LIMIT
            const minTime = this.picerMinDate - LIMIT
            return time.getTime() > maxTime || time.getTime() < minTime
          }
        }
      },
      isTooltip: false,
      deptTree: {
        deptTreeId: '',
      },
      //布控点返回数据
      roadTree: {
        roadTreeId: '',
      },
      //立即拍照传的参数
      roadTreeId: '',
      //控制按钮是否可以点击
      isDisabled: false,
      rules: RULES, // 表单校验的规则
      //推送告警短信弹窗
      dialogVisible: false,
      //推送告警短信
      pushAlertInfo: {
        photoUrlList: [],//推送的图片地址
        pushNumber: "",//推送短信的电话
        locationInfo: "",//位置信息 公路-路段-传感器
        alertTime: "",//告警时间
        earlyWarningId: "",//预警数据iD
      },
      //判断是否发送过预警
      isEarlyWarningIdUsed: false,
      card: {
        checkedCard: [] //选中的返回的数据
      },
      dataLists: [],
      control2: [], //布控点选中的组织treeid
      control: [], //布控点选中的组织treeid
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      deptTreeId: '',
      deptTree1: {
        deptTreeId: '',
      },
      form1: {page: 1, pageSize: 10},
      playMp4: false,
      imgList: [],
      constUrl,
      activeName: 'first',
      //变倍或聚焦设置

    }
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
    },
  },
  computed: {
    // 时间筛选
    timerArray: {
      get() {
        return [this.form2.startCreateTime, this.form2.endCreateTime]
      },
      set([startTimer, endTimer]) {
        this.form2.startCreateTime = startTimer
        this.form2.endCreateTime = endTimer
      }
    },
    earlyWarningId() {
      if (this.isEarlyWarningIdUsed) {
        return null
      } else {
        return this.$route.params.earlyWarningId
      }

    },
    showParameter1() {
      let type = [4, 12]
      return type.indexOf(this.form.msg_type) !== -1
    },
    cmdList() {
      let list = []
      this.EnumCameraMsgTypeList.map(x => {
        if (x.name.indexOf('下发') !== -1) {
          list.push(x)
        }
      })
      return list
    }
  },
  watch: {},
  mounted() {
    this.queryDictList(['EnumCameraMsgType'], ['EnumCameraMsgTypeList'])
  },
  methods: {

    //搜索
    search() {
      this.form1.startCreateTime = this.form2.startCreateTime
      this.form1.endCreateTime = this.form2.endCreateTime

      this.getAllPhoto()
    },
    //立即拍照录像
    action(val) {
      this.actionNow(val)
      this.isDisabled = true
      setTimeout(() => {
        this.getAllPhoto()
        this.isDisabled = false
      }, 10000)
    },
    //立即拍摄
    async actionNow(val) {
      let res = await actionNow({action: val, roadTreeId: this.roadTreeId})
    },
    //校验表单
    validateForm() {
      this.$refs.record.validate((valid) => {
        if (valid) {
          this.pushAlertMethod()
        }
      })
    },

    //推送短信
    async pushAlertMethod() {
      this.pushAlertInfo.earlyWarningId = this.earlyWarningId
      let res = await addPushRecord(this.pushAlertInfo)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '短信推送成功'
        })
        this.isEarlyWarningIdUsed = true
      }
      this.dialogVisible = false
    },
    //下载照片
    downloadImage() {
      let self = this;
      let checkedList = self.card.checkedCard;
      if (checkedList !== undefined && checkedList.length > 0) {
        var imagePathArray = [];
        for (var i = 0; i < checkedList.length; i++) {
          imagePathArray.push(checkedList[i].id);
        }
        var imgUrlString = imagePathArray.join(",")
        this.downloadPhotos(imgUrlString)
        self.card.checkedCard = [];
      } else {
        self.$notify.warning({
          title: '提示',
          message: '请选择要下载的图片'
        });
      }
    },
    //推送预警短信校验及弹窗
    pushAlert() {
      let self = this;
      let earlyWarningId = this.earlyWarningId
      let checkedList = self.card.checkedCard;
      if (!earlyWarningId) {
        self.$notify.warning({
          title: '提示',
          message: '请到预警列表选择相应的预警信息，跳转到此页面进行操作。'
        });
        return
      }
      if (checkedList !== undefined && checkedList.length > 0) {
        if (checkedList.length > 2) {
          self.$notify.warning({
            title: '提示',
            message: '只能选择两张图片'
          });
          return
        }
        self.pushAlertInfo.photoUrlList = [];
        for (var i = 0; i < checkedList.length; i++) {
          self.pushAlertInfo.photoUrlList.push(checkedList[i].photoUrl);
          self.pushAlertInfo.alertTime = checkedList[i].bizTime;
          self.pushAlertInfo.locationInfo = checkedList[i].roadName + "-" + checkedList[i].roadSectionName + "-" + checkedList[i].deviceName
        }
        self.pushAlertInfo.earlyWarningId = earlyWarningId;
        self.dialogVisible = true;
      } else {
        self.$notify.warning({
          title: '提示',
          message: '请选择需要推送图片'
        });
      }
    },

    //管养单位事件
    selectOrgHandel() {
      this.$forceUpdate() //强制刷新
      this.form1.deptTreeId = this.deptTree.deptTreeId
      this.getAllPhoto()
      this.deptTreeId = this.deptTree.deptTreeId
      this.$refs.roadTree.getOrganizationTree(this.deptTree.deptTreeId)
    },
    // 公路布控点事件
    selectOrgHandel1() {
      this.$forceUpdate()
      this.form1.deptTreeId = this.deptTreeId
      this.form1.roadTreeId = null
      this.form1.roadTreeId = this.roadTree.roadTreeId
      this.getAllPhoto()
    },
    play(src) {
      this.playMp4 = true
      this.$nextTick(()=>{
        this.singlePlayer = videojs("singleVideo", {
          autoplay: false,//自动播放
          controls: true,//控件显示
          width: "1080",//视频框宽度
          height: "364",//视频框高度
        });
        // let res='https://vjs.zencdn.net/v/oceans.mp4'
        let res=this.constUrl + src
        if (res) {
          this.singlePlayer.src({ src:res , type: "video/mp4" });
          this.singlePlayer.play();
        }
      })
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form1.pageSize = val
      this.getAllPhoto()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form1.page = val
      this.getAllPhoto()

    },
    //获取布防点数据
    async getArrangementList() {
      let res = await getArrangementList(this.deptTreeId)
      this.dataLists = res.data


    },

    //获取照片数据
    async getAllPhoto() {
      let res = await getAllPhoto(this.form1)
      this.imgList = res.data.records
      this.form1.page = Number(res.data?.current)
      this.form1.total = Number(res.data?.total)

      let roadTreeIdList = []
      if (this.form1.roadTreeId !== null && this.form1.roadTreeId !== undefined) {
        roadTreeIdList = this.form1.roadTreeId.split("-") || []
        if (roadTreeIdList.length == 3) {
          this.isDisabled = false
          this.isTooltip = true,
            this.roadTreeId = this.form1.roadTreeId
        } else {
          this.isDisabled = true
          this.isTooltip = false
        }
      } else {
        this.isDisabled = true
        this.isTooltip = false
      }

    },
    //下载照片
    async downloadPhotos(val) {
      await downloadPhotos({ids: val})
      //    this.downloadFile( await downloadPhotos({imgUrls: val}))
    },
    // 查看大图
    previewImg(index) {
      this.$refs.imageViewer.showViewer(this.imgList.map(x => this.constUrl + x.photoUrl), index, this.imgList.map(x => x.arrangementName))
    },
    playVideo(src) {
      this.$refs['playerObj'].playerOptions.sources[0].src = src
    },
    //选择指令，处理表单内容
    changeMsg(val) {
      if (val === 4) {
        this.form = {
          msg_type: val,
          action: 0,
          http_url: 'http://8.134.54.223:10000/record/camera-photo-record/v1/upload',
          width: 1080,
          height: 720,
          wdr: 0,
          codec: 0,
          count: 1,
        }
      } else if (val === 12) {
        this.form = {
          msg_type: val,
          http_url: 'rtmp://hofuniot.cn:4199/live/356802050202455?user=test&sign=fb486b56434f22c70ac659ed1ac6cf06',
          mode: 0,
          wdr: 0,
          codec: 0,
        }
      } else if (val === 20) {
        this.form = {
          msg_type: val,
          mode: 0,
        }
      } else if (val === 28) {
        this.form = {
          msg_type: val,
          set_flag: 0,
        }
      } else {
        this.form = {
          msg_type: val
        }
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        let div = document.getElementById('data-list-content')
        div.scrollTop = div.scrollHeight
      })
    },
    alertMes(mes) {
      this.$message(
        {
          type: 'error',
          showClose: true,
          message: '请填入参数:' + mes
        })
    },
    changeDataInfoToJson: function () {
      var self = this
      var str = self.dataInfo
      try {
        str = str.replace(/ \+/g, '')
        str = str.replace(/[\r\n]/g, '')
        self.dataInfo = str
        let parseJSON = JSON.parse(self.dataInfo)
        self.dataInfo = JSON.stringify(parseJSON, null, 2)
      } catch (err) {
        this.$message(
          {
            type: 'error',
            showClose: true,
            message: '请传入正确的json数据！，也可通过：https://www.bejson.com/ 进行转换'
          })
      }
    }
    ,
    /**
     * 获得当前 年月日时分秒格式时间
     * @returns {string}
     */
    getNowDate: function () {
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
    }
    ,
  }
  ,

}
</script>
<style scoped lang="less">
  .btnNo {
    background: #d5d5d5 !important;
    color: #939292 !important;
    border: #939292 !important;
  }

  .info-input {
    color: #228AF5;
    margin-left: 20px;
    font-weight: 600;
    font-size: 17px;
  }

  .info-parameter {
    color: #2dca7f;
    margin-left: 20px;
    font-weight: 600;
    font-size: 15px;
  }

  .input {
    width: 150px;
  }

  .el-select {
    width: 150px;
  }

  .heads {
    padding-top: 20px;
    /*height: 400px !important;*/
    height: auto !important;
    margin: 0 auto;
    width: 100%;
  }

  .middle {

    width: 100%;
    min-height: 600px;
    margin: 20px auto;
    display: flex;
    /*align-items: center;*/
    justify-content: center;
    text-align: center;


  }

  .el-button--success {
    background-color: #67c23a;
  }

  .p-show {
    margin-top: 8px;
  }

  .el-main {
    overflow-y: auto;
  }

  .param-view {
    margin-top: 5px;
  }

  .el-divider--horizontal {
    margin: 15px 0;
  }

  .base_img {
    display: inline-block;

    .el-button--text {
      color: black;
    }


    width: 175px;

    .base_img-item {

      height: 175px;
      cursor: pointer;
    }

    .base_img-name {
      padding: 10px 6px;
    }

    .base_img-time {
      font-size: 12px;
      padding: 0 6px 6px;
      color: #999;

      p {
        margin: 10px 0;
      }
    }
  }

  .h3Title {
    width: 100%;
    height: 40px;
    background: linear-gradient(to right, #1990FE, rgba(25, 144, 254, 0.5), rgba(25, 144, 254, 0.2));
    line-height: 40px;
    box-sizing: border-box;
    padding-left: 20px;
    color: white;
    font-size: 20px;
    font-weight: 600
  }

  .org_view {
    background-color: white;
    height: calc(100vh - 93px);
    position: relative;
    overflow: hidden;
    box-shadow: 2px 2px 8px #757575;
    box-shadow: 2px 2px 4px #ababab;
  }

  /deep/ .el-tree-node__label {
    font-weight: 600 !important;
    width: 120% !important;
    height: 40px;
    line-height: 40px;
  }

  /deep/ .el-tree-node__content:hover {
    font-weight: 600 !important;
    background: linear-gradient(to right, #1990FE, rgba(25, 144, 254, 0.8), rgba(25, 144, 254, 0.5), rgba(25, 144, 254, 0.3)) !important;
    color: white !important;
  }

  /deep/ .el-tree-node__content:hover {
    font-size: 120% !important;
  }

  /deep/ .el-tree-node__label:active {
    font-weight: 600 !important;
    color: white !important
  }

  /deep/ .el-tree-node__content {
    height: 40px;
    line-height: 40px;
    /*padding: 10px 0px !important;*/
    margin-left: 10px;
    border-radius: 0px 5px 5px 0px !important;
    margin: 2px 0;
    margin-left: 5px;
  }

  /deep/ .el-tree-node.is-current > .el-tree-node__content {
    border-radius: 0px 5px 5px 0px !important;
  }

  /deep/ .el-checkbox__inner {
    border: 1px solid #1990FE;
  }
</style>
